﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using System.Diagnostics;

namespace Macaw.Wss3.DependencySpiderSolution
{

    public class SPSiteIndexer
    {
        #region Private properties
        private DependencyMap dependencymap;
        private AddOrGetResourceDelegate addorgetresource;
        #endregion

        public long IndexCount;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="dependencymap"></param>
        /// <param name="addorgetresource"></param>
        public SPSiteIndexer(DependencyMap dependencymap, AddOrGetResourceDelegate addorgetresource)
        {
            this.dependencymap = dependencymap;
            this.addorgetresource = addorgetresource;
        }

        private void IndexSiteCollectionFile(SPSite site, SPFile file)
        {
            #region Add "resource" for each AlternateUrl
            foreach (SPAlternateUrl alturl in site.WebApplication.AlternateUrls)
            {
                if (addorgetresource != null)
                {
                    string url = SPUrlUtility.CombineUrl(alturl.IncomingUrl, file.ServerRelativeUrl);
                    Trace.WriteLine(string.Format("Adding \"{0}\" to map." , url));
                    DependencyMap.ResourceRow resourcerow = addorgetresource(dependencymap, url);
                    resourcerow.SPID = file.UniqueId;
                }
            }
            #endregion
        }

        /// <summary>
        /// Index SiteCollection
        /// </summary>
        /// <param name="sitecollection"></param>
        public void Index(SPSite sitecollection)
        {
            foreach (SPWeb web in sitecollection.AllWebs)
            {
                if (web.AllowAnonymousAccess)
                {
                    foreach (SPFolder folder in web.Folders)
                    {
                        foreach (SPFile file in folder.Files)
                        {
                            try
                            {
                                if (file.Item != null && file.Item.ParentList != null && (file.Item.ParentList.AnonymousPermMask64 & SPBasePermissions.ViewListItems) == SPBasePermissions.ViewListItems)
                                {
                                    IndexSiteCollectionFile(sitecollection, file);
                                    IndexCount++;
                                }
                            }
                            catch (Exception)
                            {
                                System.Diagnostics.Trace.WriteLine(string.Format("Unable to Index \"{0}\" in web \"{1}\"", file.Url, web.Url));
                            }
                        }
                    }
                }
            }

        }
    }
}
